We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Why should I call $di->getSession() in order to synchronize Phalcon sessions and PHP sessions ?

The Phalcon version is 2.0.8

I set the session service in the public index.php file :

use Phalcon\Session\Adapter\Files as SessionFiles; try { ... $di = new FactoryDefault();

// Start the session the first time when some component request the session service
$di->setShared('session', function () {
    $session = new SessionFiles();
    $session->start();
    return $session;
});
....

}

When I set a Phalcon session variable then I cannot get the equivalent $_SESSION PHP variable unless I write this code :

$di = \Phalcon\DI::getDefault(); $session = $di->getSession();

So Why should I call this code to synchronize Phalcon sessions and PHP sessions ?



3.6k
edited Feb '16

When you place something in the dependency injection container, it is not actually used until you retrieve that specific item from the container. We call this the 'lazy loading' design pattern and it avoids spending computer time and memory on creating and storing objects that are going unused. This means that the function that you added to the container is not executed until you use the session item.

Once you call getSession() on the DI, it calls the function you added to it which creates the SessionFiles object and calls start() on it, which in turn calls the php function session_start() and enables the $_SESSION variable.

You might also want to consider to use the session object in your DI directly instead of relying on $_SESSION though.